package com.example.gateway.filer;

import com.example.gateway.util.MonoUtil;
import com.example.gateway.util.map.CommonModel;
import com.example.gateway.util.map.MapUtil;
import com.example.gateway.util.map.ModelTool;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 描述
 *
 * @author Huzz
 * @create 2022-07-15 15:03
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            // 封装错误信息
            Map<String, Object> result = Maps.newHashMap();
            result.put("code", 401);
            result.put("message", "非法请求");
            result.put("cause", "Token is empty");

            return MonoUtil.noAuth(exchange,result);
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}
